import React from 'react';
import {InputGroup} from "@blueprintjs/core";
import {AppToaster} from "../../component/Toast";
import axios from '../../config/axios';
import {host} from '../../config/host';
import { connect } from "react-redux";
import { userActions } from '../../store/user';
import {withRouter } from 'react-router';

import './index.less'

class Login extends React.PureComponent {
    constructor(props) {
        super(props)
        this.handleLogin = this.handleLogin.bind(this);
        this.state = {
            disabled: false,
            filterValue: "",
            large: false,
            showPassword: false,
            small: false,
            tagValue: "",
            UserId: null,
            Password: null
        }
    }

    async handleLogin() {
        const {UserId, Password} = this.state;
        const data = {UserId, Password}
        try {
            const msg = await axios.post(host + "login", data);
            if (msg.data.statusCode === 0) {
                AppToaster.show({ message: msg.data.statusInfo });
            } else {
                AppToaster.show({ message: "登录成功" });
                const {changeUserId, changeOrg, changeRole, changePermission} = this.props
                const data = JSON.parse(msg.data.statusMsg);
                const { userId, org, role, add, edit} = data;
                const deleteData = data.delete
                changeUserId({userId})
                changeOrg({org})
                changeRole({role})
                changePermission({
                    add, edit,
                    delete: deleteData
                })
                this.props.history.push('/');
            }
        } catch (e) {
            console.log(e)
            AppToaster.show({ message: "帐号或者密码错误" });
        }
    }

    handleInputValue(type, e) {
        let state = this.state;
        state[type] = e.target.value;
        this.setState(state)
    }

    render() {
        const { disabled, large, small, showPassword } = this.state;
        return (<div className="Login">
                <InputGroup
                    disabled={disabled}
                    large={large}
                    placeholder="用户名"
                    small={small}
                    type={"text"}
                    onChange={(event)=> this.handleInputValue("UserId", event)}
                />
                <InputGroup
                    disabled={disabled}
                    large={large}
                    placeholder="密码"
                    small={small}
                    type={showPassword ? "text" : "password"}
                    onChange={(event)=> this.handleInputValue("Password", event)}
                />
                <a role="button" className="bp3-button" tabIndex="0" onClick={this.handleLogin}>登录</a>
        </div>);
    }
}

export default withRouter(connect(null, userActions)(Login))